package com.share;

import hipro.entities.Events;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EventActivity extends BaseActivity {
	private hipro.event.Events webserviceEvent;
	private String username = "";
	private String password = "";
	private SharedPreferences settings;
	private LocationManager locationManager;
	private MyLocationListenner mL;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.event_list);

		mL = new MyLocationListenner();
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, mL);

		// set view events
		webserviceEvent = new hipro.event.Events();
		webserviceEvent.setWebservice(getString(R.string.webservice_event));

		this.setValueAccount();
		try {
			this.showList();
		} catch (Exception e) {
			this.showList();
		}
		
		//this.listEventsByUserId();
	}

	/**
	 * Create menu
	 * 
	 * @author NguyenVanTien
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	/**
	 * Click choose some menu
	 * 
	 * @author NguyenVanTien
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuCountry: {
			Intent iCountry = new Intent(this, CountryActivity.class);
			startActivity(iCountry);
			break;
		}
		case R.id.menuCategory: {
			Intent iCategory = new Intent(this, CategoryActivity.class);
			startActivity(iCategory);
			break;
		}
		case R.id.menuUser: {
			Intent iUser = new Intent(this, UserActivity.class);
			startActivity(iUser);
			break;
		}
		case R.id.menuComment : {
			Intent iComments = new Intent(this, CommentsActivity.class);
			startActivity(iComments);
			break;
		}
		
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * Set value account login
	 */
	private void setValueAccount() {
		SharedPreferences settings = getSharedPreferences("pref_login", 0);
		this.username = settings.getString("username", "");
		this.password = settings.getString("password", "");

	}
	
	public void listEventsByUserId(){
		ArrayList<hipro.entities.Events> list =
			new ArrayList<hipro.entities.Events>();
		
		list = this.webserviceEvent.listEventsByUserId(this.username, 
				this.password, 1, 0, 1);
		
		String str = "";
		for(hipro.entities.Events event : list){
			str += event.getEventDetail()+"   test";
		}
		AlertDialog al = new AlertDialog.Builder(this).create();
		al.setMessage(str);
		al.show();
	}

	/**
	 * Show event
	 * 
	 * @author Tien Nguyen
	 * @param eventId
	 */
	public void showEvent(int eventId) {
		setContentView(R.layout.event_detail);

		hipro.entities.Events event = webserviceEvent.getEvent(this.username,
				this.password, eventId);
		TextView textEventTitle = (TextView) findViewById(R.id.textEventTitle);
		TextView textEventDetail = (TextView) findViewById(R.id.textEventDetail);
		TextView textEventId = (TextView) findViewById(R.id.txtEventId);

		Button btnBack = (Button) findViewById(R.id.btnEventBack);
		Button btnDelete = (Button) findViewById(R.id.btnEventDelete);
		Button btnAdd = (Button) findViewById(R.id.btnEventAdd);

		textEventTitle.setText(event.getEventName());
		textEventDetail.setText(event.getEventDetail());
		textEventId.setText(event.getEventId() + "");

		btnBack.setOnClickListener(new btnBackEventList());
		btnDelete.setOnClickListener(new btnDeleteEvent());
		btnAdd.setOnClickListener(new btnAddEvent());
		
		Toast.makeText(this, event.getUserId()+" user id", Toast.LENGTH_LONG).show();
	}

	/**
	 * show form for add event
	 */
	public void addEvent() {
		setContentView(R.layout.event_add);

		mL = new MyLocationListenner();
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, mL);

		final EditText title = (EditText) findViewById(R.id.eventAddTitle);
		final EditText content = (EditText) findViewById(R.id.eventAddContent);
		Button btnSave = (Button) findViewById(R.id.eventAddSave);
		Button btnCancel = (Button) findViewById(R.id.eventAddCancel);
		final Spinner spinner = (Spinner) findViewById(R.id.addEventCategory);

		ArrayList<hipro.entities.EventCategories> list = new ArrayList<hipro.entities.EventCategories>();
		list = this.webserviceEvent.listEventCategories(this.username,
				this.password);

		// general array for spinner
		ArrayList<HashMap<String, String>> ls = new ArrayList<HashMap<String, String>>();
		for (hipro.entities.EventCategories eventCategory : list) {
			System.out.println(eventCategory.toString());
			HashMap<String, String> obj = new HashMap<String, String>();
			obj.put("eventCategoryId", eventCategory.getEventCategoryId() + "");
			obj.put("eventCategoryName", eventCategory.getEventCategoryName());
			ls.add(obj);
		}
		;

		String[] from = { "eventCategoryName", "eventCategoryId" };
		int[] to = { android.R.id.text1, android.R.id.text2 };

		// ArrayAdapter<EventCategories> adapter = new
		// ArrayAdapter<EventCategories>(
		// this, android.R.layout.simple_list_item_1, list);

		SimpleAdapter adapter = new SimpleAdapter(this, ls,
				android.R.layout.simple_spinner_item, from, to);

		spinner.setAdapter(adapter);

		final SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");

		/**
		 * Action save button
		 */
		btnSave.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				// select item
				HashMap<String, String> item = (HashMap<String, String>) spinner
						.getSelectedItem();

				EventActivity.this.settings = getSharedPreferences(
						"pref_login", 0);

				// TODO Auto-generated method stub
				hipro.entities.Events event = new Events();
				event.setEventName(title.getText().toString());
				event.setEventDetail(content.getText().toString());
				event.setCreatedDate(dateFormat.format(new Date()).toString());
				event.setEventCategoryId(Integer.parseInt(item
						.get("eventCategoryId")));
				event.setLat(EventActivity.this.settings
						.getString("lat", "0.0"));
				event.setLng(EventActivity.this.settings
						.getString("lng", "0.0"));
				event.setVisible(true);

				EventActivity.this.webserviceEvent.addEvent(
						EventActivity.this.username,
						EventActivity.this.password, event);

				EventActivity.this.showList();
			}
		});

		/**
		 * cancel show show event
		 */
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EventActivity.this.showList();
			}
		});

	}

	/**
	 * Show event
	 */
	private void showList() {
		try {
			setContentView(R.layout.event_list);
			List<hipro.entities.Events> events = webserviceEvent.listEvents(
					this.username, this.password, "10", "10");

			String[] from = new String[] { "eventDetail", "event_date" };
			int[] to = new int[] { R.id.title, R.id.event_date };

			// prepare the list of all records
			List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

			for (hipro.entities.Events event : events) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("eventDetail", event.getEventDetail());
				map.put("eventId", event.getEventId() + "");
				map.put("event_date", event.getCreatedDate().toString());
				fillMaps.add(map);
			}

			// SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
			// R.layout.event_row, from, to);

			CustomerAdapter adapter = new CustomerAdapter(this, fillMaps,
					R.layout.event_row, from, to);

			ListView listView = (ListView) findViewById(R.id.list_events);
			listView.setTextFilterEnabled(true);
			listView.setAdapter(adapter);

			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					System.out.println("sf");

				}
			});
		} catch (Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
	}

	public class CustomerAdapter extends SimpleAdapter {

		List<? extends Map<String, ?>> data;

		public CustomerAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.data = data;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v = super.getView(position, convertView, parent);

			final int pos = position;
			final long id = getItemId(position);
			final List<? extends Map<String, ?>> datam = this.data;

			v.findViewById(R.id.btnDetail).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							int eventId = Integer.parseInt((String)datam.get(pos).get("eventId"));
							System.out.println(id + " this is id of item");
							System.out.println(datam.get(pos).get("eventId")
									+ " this is value of id");
							EventActivity.this.showEvent(eventId);
						}
					});

			return v;
		}

	}

	public class MyLocationListenner implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			Log.d("Tien",
					location.getLatitude() + "   " + location.getLongitude());
			// save to ref
			SharedPreferences settings = getSharedPreferences("pref_login", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("lat", location.getLatitude() + "");
			editor.putString("lng", location.getLongitude() + "");
			editor.commit();
		}

		@Override
		public void onProviderDisabled(String provider) {
			Log.d("Tien", "onProviderDisabled");

			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Log.d("Tien", "onProviderEnabled");
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			Log.d("Tien", "onStatusChanged");
		}

	}

	/**
	 * Delete event
	 * 
	 * @author NguyenVanTien
	 * 
	 */
	public class btnDeleteEvent implements OnClickListener {

		@Override
		public void onClick(View v) {
			TextView txtEventId = (TextView) EventActivity.this
					.findViewById(R.id.txtEventId);

			int eventId = Integer.parseInt(txtEventId.getText().toString());

			EventActivity.this.webserviceEvent.removeEvent(
					EventActivity.this.username, EventActivity.this.password,
					eventId);

			// show list
			EventActivity.this.showList();
		}
	}

	/**
	 * Add event
	 * 
	 * @author NguyenVanTien
	 * @author NguyenVanTien
	 * 
	 */
	public class btnAddEvent implements OnClickListener {

		@Override
		public void onClick(View v) {
			EventActivity.this.addEvent();
		}

	}

	/**
	 * Action bacl
	 * 
	 * @author NguyenVanTien
	 * 
	 */
	public class btnBackEventList implements OnClickListener {

		@Override
		public void onClick(View v) {
			System.out.println("Action event back list");
			EventActivity.this.showList();
		}

	}
}
